import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter_my_web/widget/TextWidget.dart';


//使用Path lineTo方式添加线 减少点的绘制
class SketchPad_2 extends StatefulWidget {
  const SketchPad_2({Key? key}) : super(key: key);

  @override
  State<SketchPad_2> createState() => _SketchPad_2State();
}

class _SketchPad_2State extends State<SketchPad_2> {
   Path lastPath=Path();
   Path curPath = Path();
  int points = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onPanDown: (details) {
          setState(() {
            points++;
            curPath.moveTo(details.localPosition.dx, details.localPosition.dy);
            curPath.lineTo(details.localPosition.dx+1, details.localPosition.dy+1);
          });
        },
        onPanUpdate: (details) {
          setState(() {
            curPath.lineTo(details.localPosition.dx, details.localPosition.dy);
          });
        },
        onPanEnd: (_) {
          lastPath.addPath(curPath, Offset.zero);
          curPath = Path();
        },
        child: Stack(
          children: [
            // CustomPaint(
            //   painter: _SketchPainter(lastPath,true),
            //   size: Size.infinite,
            //   willChange: false,
            //   isComplex: true,
            // ),
            Container(
              height: double.infinity,
              width: double.infinity,
              color: Colors.yellow[100],
              child: SimpleText("${points}"),
            ),
            CustomPaint(
              foregroundPainter: _SketchPainter(lastPath,true),
              painter: _SketchPainter(curPath,false),
              size: Size.infinite,
            ),
          ],
        ));
  }
}

class _SketchPainter extends CustomPainter {
  Path? paths;
  bool islast = false;
  _SketchPainter(this.paths,this.islast);

  static final pen = Paint()
    ..color = Colors.black
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;

  @override
  void paint(Canvas canvas, Size size) {
    if(paths!=null){
      canvas.drawPath(paths!, pen);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return !islast;
  }
}
